<?php

namespace app\common\model;

use app\common\util\Tools;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 系统配置表
 */
class trSystemSet extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "system_set"; //表名

    public static function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        return $data;
    }

    //根据条件获取数量
    public static function getCount($filter){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            return self::count();
        }
    }

    //保存
    public static function toSave($value = [], $key = ""){
        if(!$value || !$key)
            return false;
        $mall_id = request()->mallData["id"];
        if((C_get("{$mall_id}_isExist_s_{$key}")) !== false || self::getCount(["key" => $key, "mall_id" => $mall_id])){ //更新
            $result = self::where("key", $key)->where("mall_id", $mall_id)->update(["value" => serialize($value)]);
            if ($result) {
                C_set("{$mall_id}_".$key, $value);
                C_set("{$mall_id}_"."isExist_s_{$key}", true);
                return true;
            }
            if ($result === 0) {
                return true;
            }
        }else{
            if(self::create(["value" => serialize($value), "key" => $key, "mall_id" => $mall_id])){
                C_set("{$mall_id}_".$key, $value);
                C_set("{$mall_id}_"."isExist_s_{$key}", true);
                return true;
            }
        }
        return false;
    }

    //获取某字段的值
    public static function getValue($key){
        if (empty($key)) {
            return false;
        }
        $mall_id = request()->mallData["id"];
        if(($data = C_get("{$mall_id}_".$key)) === false){
            $item = self::where("key", $key)->where("mall_id", $mall_id)->field("value")->find();
            if(empty($item["value"])) {
                return false;
            }
            $data = unserialize($item["value"]);
            C_set("{$mall_id}_".$key, $data);
        }
        return $data;
    }

    //根据删除数据
    public static function del($key){
        if (empty($key)) {
            return false;
        }
        $mall_id = request()->mallData["id"];
        if (!is_array($key)) {
            C_set("{$mall_id}_".$key, null);
            C_set("{$mall_id}_"."isExist_s_".$key, null);
            $filter = ["key" => $key, "mall_id" => $mall_id];
        }else{
            foreach ($key as $id){
                C_set("{$mall_id}_".$id, null);
                C_set("{$mall_id}_"."isExist_s_".$id, null);
            }
            $filter = [["key", "in", $key], ["mall_id", "=", $mall_id]];
        }
        $result = self::where($filter)->delete();
        return $result;
    }
}